package com.enzoism.manual.springboot.config.shiro;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: SpringCloud
 * @description: Shiro配置文件
 * @author: zhifeng
 * @create: 2020-12-08 10:53
 */
@Configuration
public class ShiroConfig {



    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> filterChain = new LinkedHashMap<String, String>();
        // 登陆即可访问
        filterChain.put("/user/add","authc");
        filterChain.put("/user/edit","authc");

        // 权限升级【登陆后并且需要指定权限才能访问】
        filterChain.put("/user/*","authc");
        filterChain.put("/user/add","perms[user:add]");
        filterChain.put("/user/edit","perms[user:edit]");
        filterChain.put("/**/", "anon");
        filterFactoryBean.setFilterChainDefinitionMap(filterChain);

        // 没有权限跳转登陆页面
        filterFactoryBean.setLoginUrl("/toLogin");
        // 没有授权跳转页面
        filterFactoryBean.setUnauthorizedUrl("/noauth");

        return filterFactoryBean;
    }


    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    @Bean(name = "userRealm")
    public UserRealm getUserRealm(){
        return new UserRealm();
    }
}
